import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/picker_style.dart';
import 'package:get/get.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/controller/userInfo_controller.dart';
import 'package:live_music/http/http_utils.dart';

import 'package:live_music/models/user_info_model.dart';
import 'package:live_music/utils/toast_utils.dart';
import 'package:live_music/utils/util.dart';

class EditUserInfoPage extends StatefulWidget {
  EditUserInfoPage({Key key, this.editType}) : super(key: key);
  final String editType;
  @override
  _EditUserInfoPageState createState() => _EditUserInfoPageState();
}

class _EditUserInfoPageState extends State<EditUserInfoPage>
    with SingleTickerProviderStateMixin {
  UserInfoModel userInfo = UserInfoModel();
  TextEditingController _userNameEditController;
  TextEditingController _desEditController;
  TextEditingController _schoolEditController;
  String birthday;
  String cityStringArr;
  int gender;
  final _userInfoController = Get.find<UserInfoController>();
  bool isShowGender;
  bool isShowBirthday;
  bool isShowCity;
  bool isShowSchool;
  int showBirthdayType;
  bool flag;
  @override
  void initState() {
    super.initState();
    _userNameEditController = TextEditingController();
    _desEditController = TextEditingController();
    _schoolEditController = TextEditingController();
    loadUserInfo();
  }

  loadUserInfo() async {
    switch (widget.editType) {
      case "昵称":
        _userNameEditController.text = _userInfoController.userInfo.value.name;
        break;
      case "简介":
        _desEditController.text =
            _userInfoController.userInfo.value.description;
        break;
      case "学校":
        _schoolEditController.text =
            _userInfoController.userInfo.value.university;
        isShowSchool = _userInfoController.userSetting.value.isShowSchool == 1
            ? true
            : false;
        break;
      case "生日":
        setState(() {
          birthday = _userInfoController.userInfo.value.birthday;
          showBirthdayType =
              _userInfoController.userSetting.value.isShowBirthday;
          isShowBirthday =
              _userInfoController.userSetting.value.isShowBirthday != 0
                  ? true
                  : false;
        });
        break;
      case "性别":
        setState(() {
          gender = _userInfoController.userInfo.value.gender;
          isShowGender = _userInfoController.userSetting.value.isShowGender == 1
              ? true
              : false;
        });
        break;
      case "地区":
        setState(() {
          isShowCity = _userInfoController.userSetting.value.isShowCity == 1
              ? true
              : false;
          cityStringArr = _userInfoController.userInfo.value.province +
              "-" +
              _userInfoController.userInfo.value.city;
        });
        break;
    }
  }

  _updateUserInfo() async {
    Map<String, dynamic> data = {};
    Map<String, dynamic> settingData = {};
    switch (widget.editType) {
      case "昵称":
        data['name'] = _userNameEditController.text;
        break;
      case "简介":
        data['description'] = _desEditController.text;
        break;
      case "学校":
        data['university'] = _schoolEditController.text;
        settingData["isShowSchool"] = isShowSchool == true ? 1 : 0;
        _userInfoController.updateUserSetting(settingData);
        break;
      case "生日":
        data['birthday'] = birthday;
        settingData["isShowBirthday"] = isShowBirthday == true ? 1 : 0;
        if (isShowBirthday == true && showBirthdayType != 0) {
          settingData["isShowBirthday"] = showBirthdayType;
        }
        _userInfoController.updateUserSetting(settingData);
        break;
      case "地区":
        data['cityStringArr'] = cityStringArr;
        settingData["isShowCity"] = isShowCity == true ? 1 : 0;
        _userInfoController.updateUserSetting(settingData);
        break;
      case "性别":
        data['gender'] = gender;
        settingData["isShowGender"] = isShowGender == true ? 1 : 0;
        _userInfoController.updateUserSetting(settingData);
        break;
    }
    _userInfoController.updateUserInfo(data);
    Future.delayed(Duration(milliseconds: 500), () {
      Get.back();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: PreferredSize(
            preferredSize: Size.fromHeight(50),
            child: AppBar(
              elevation: 0.0,
              centerTitle: true,
              title: Center(
                child: Container(
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      GestureDetector(
                        child: Text(
                          "取消",
                          style: TextStyle(
                              fontSize: 16,
                              color: Colors.grey,
                              fontWeight: FontWeight.w500),
                        ),
                        onTap: () {
                          Get.back();
                        },
                      ),
                      Container(
                        child: Text(
                          "编辑" + widget.editType,
                          style: TextStyle(
                              fontSize: 16,
                              color: Colors.black,
                              fontWeight: FontWeight.w500),
                        ),
                      ),
                      InkWell(
                        child: Container(
                          child: Text(
                            "保存",
                            style: TextStyle(
                                fontSize: 16,
                                color: Colors.redAccent,
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                        onTap: _updateUserInfo,
                      )
                    ],
                  ),
                ),
              ),
              automaticallyImplyLeading: false,
            )),
        body: Column(children: [_buildEditType()]));
  }

  Widget _buildEditType() {
    Widget editTypeWidget;
    switch (widget.editType) {
      case "昵称":
        editTypeWidget = _buildName();
        break;
      case "简介":
        editTypeWidget = _buildDes();
        break;
      case "性别":
        editTypeWidget = _buildGender();
        break;
      case "生日":
        editTypeWidget = _buildBirthday();
        break;
      case "地区":
        editTypeWidget = _buildArea();
        break;
      case "学校":
        editTypeWidget = _buildSchool();
        break;
    }
    return editTypeWidget;
  }

  Widget _buildArea() {
    return Container(
        child: Column(children: [
      Cell(
        '地区',
        onTap: () {
          String initProvince = '广东省', initCity = '广州市';
          Pickers.showAddressPicker(
            context,
            initProvince: initProvince,
            initCity: initCity,
            addAllItem: false,
            pickerStyle: PickerStyle(
                commitButton: Container(
              padding: EdgeInsets.symmetric(horizontal: 20),
              child: Text("确认", style: TextStyle(color: Colors.blue)),
            )),
            onConfirm: (p, c, t) {
              print(p);
              setState(() {
                cityStringArr = p + "-" + c;
              });
            },
          );
        },
        right: Container(
          height: 20,
          child: Text(
            cityStringArr,
            style: TextStyle(fontSize: WcaoTheme.fsL),
          ),
        ),
      ),
      Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        alignment: Alignment.centerLeft,
        margin: EdgeInsets.only(top: 24),
        child: Text(
          '是否在个人页展示',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
      ),
      Cell('展示地区标签',
          onTap: () {},
          showRight: false,
          right: Container(
            height: 20,
            child: Switch(
                activeColor: Colors.redAccent,
                value: isShowCity,
                onChanged: (value) {
                  setState(() {
                    isShowCity = value;
                  });
                }),
          ))
    ]));
  }

  Widget _buildBirthday() {
    return Container(
        child: Column(children: [
      Cell(
        '生日信息',
        onTap: () {
          DatePicker.showDatePicker(context,
              dateFormat: "yyyy MM dd", //通过空格设置滚轮数量
              pickerTheme: DateTimePickerTheme(
                  confirm: Text("确认",
                      style: TextStyle(fontSize: 14, color: Colors.blue))),
              onConfirm: (DateTime dateTime, List<int> selectedIndex) {
            setState(() {
              birthday = dateTime.year.toString() +
                  '-' +
                  (dateTime.month < 10
                      ? "0" + dateTime.month.toString()
                      : dateTime.month.toString()) +
                  '-' +
                  (dateTime.day < 10
                      ? "0" + dateTime.day.toString()
                      : dateTime.day.toString());
            });
            print(birthday);
          });
        },
        right: Container(
          height: 20,
          child: Text(
            birthday,
            style: TextStyle(fontSize: WcaoTheme.fsL),
          ),
        ),
      ),
      Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        alignment: Alignment.centerLeft,
        margin: EdgeInsets.only(top: 24),
        child: Text(
          '是否在个人页展示',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
      ),
      Cell('展示生日标签',
          onTap: () {},
          showRight: false,
          right: Container(
            height: 20,
            child: Switch(
                activeColor: Colors.redAccent,
                value: isShowBirthday,
                onChanged: (value) {
                  setState(() {
                    isShowBirthday = value;
                  });
                }),
          )),
      Container(
        margin: EdgeInsets.symmetric(horizontal: 16),
        padding: EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(20)),
        child: Column(children: [
          InkWell(
              onTap: () {
                setState(() {
                  showBirthdayType = 2;
                });
              },
              child: Container(
                  padding: EdgeInsets.symmetric(vertical: 16),
                  decoration: BoxDecoration(
                      border: Border(
                    bottom: BorderSide(width: .5, color: Colors.grey[200]),
                  )),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '展示年龄',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.black,
                        ),
                      ),
                      showBirthdayType == 2
                          ? Container(
                              width: 18,
                              height: 18,
                              child: Image.asset(
                                'assets/images/icons/gouzi.png',
                                fit: BoxFit.fill,
                              ),
                            )
                          : Container(),
                    ],
                  ))),
          InkWell(
              onTap: () {
                setState(() {
                  showBirthdayType = 1;
                });
              },
              child: Container(
                  padding: EdgeInsets.symmetric(vertical: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '展示星座',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.black,
                        ),
                      ),
                      showBirthdayType == 1
                          ? Container(
                              width: 18,
                              height: 18,
                              child: Image.asset(
                                'assets/images/icons/gouzi.png',
                                fit: BoxFit.fill,
                              ),
                            )
                          : Container(),
                    ],
                  )))
        ]),
      ),
    ]));
  }

  Widget _buildGender() {
    return Container(
        child: Column(
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.symmetric(vertical: 12),
          child: Text(
            '选择你的性别',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.symmetric(horizontal: 16),
          padding: EdgeInsets.symmetric(horizontal: 16),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(20)),
          child: Column(children: [
            Container(
                padding: EdgeInsets.symmetric(vertical: 16),
                decoration: BoxDecoration(
                    border: Border(
                  bottom: BorderSide(width: .5, color: Colors.grey[200]),
                )),
                child: InkWell(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '男',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.black,
                        ),
                      ),
                      gender == 1
                          ? Container(
                              width: 18,
                              height: 18,
                              child: Image.asset(
                                'assets/images/icons/gouzi.png',
                                fit: BoxFit.fill,
                              ),
                            )
                          : Container(),
                    ],
                  ),
                  onTap: () {
                    setState(() {
                      gender = 1;
                    });
                  },
                )),
            Container(
                padding: EdgeInsets.symmetric(vertical: 16),
                child: InkWell(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '女',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.black,
                        ),
                      ),
                      gender == 0
                          ? Container(
                              width: 18,
                              height: 18,
                              child: Image.asset(
                                'assets/images/icons/gouzi.png',
                                fit: BoxFit.fill,
                              ),
                            )
                          : Container(),
                    ],
                  ),
                  onTap: () {
                    setState(() {
                      gender = 0;
                    });
                  },
                ))
          ]),
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.only(top: 24),
          child: Text(
            '是否在个人页展示',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
        ),
        Cell(
          '展示性别标签',
          onTap: () {},
          showRight: false,
          right: Container(
            height: 20,
            child: Switch(
                activeColor: Colors.redAccent,
                value: isShowGender,
                onChanged: (value) {
                  setState(() {
                    isShowGender = value;
                  });
                }),
          ),
        ),
      ],
    ));
  }

  Widget _buildSchool() {
    return Container(
        child: Column(children: [
      Container(
        margin: const EdgeInsets.only(top: 24, bottom: 12, left: 15, right: 15),
        height: 70,
        child: TextField(
          controller: _schoolEditController,
          onChanged: (value) {
            setState(() {
              // checkLoginText();
            });
          },
          cursorColor: Colors.redAccent,
          enableSuggestions: false,
          autocorrect: false,
          maxLength: 30,
          decoration: InputDecoration(
            hintText: "请输入学校",
            filled: true,
            fillColor: Colors.white,
            contentPadding:
                const EdgeInsets.symmetric(vertical: 0, horizontal: 16),
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(20),
                borderSide: BorderSide(color: Colors.white, width: 2.0)),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(20),
              borderSide: BorderSide(
                color: Colors.white,
                width: 2,
              ),
            ),
          ),
        ),
      ),
      Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        alignment: Alignment.centerLeft,
        margin: EdgeInsets.only(top: 24),
        child: Text(
          '是否在个人页展示',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
      ),
      Cell(
        '展示学校标签',
        onTap: () {},
        showRight: false,
        right: Container(
          height: 20,
          child: Switch(
              activeColor: Colors.redAccent,
              value: isShowSchool,
              onChanged: (value) {
                setState(() {
                  isShowSchool = value;
                });
              }),
        ),
      ),
    ]));
  }

  Widget _buildName() {
    return Container(
      margin: const EdgeInsets.only(top: 24, bottom: 12, left: 15, right: 15),
      height: 70,
      child: TextField(
        controller: _userNameEditController,
        onChanged: (value) {
          setState(() {
            // checkLoginText();
          });
        },
        cursorColor: Colors.redAccent,
        enableSuggestions: false,
        autocorrect: false,
        maxLength: 12,
        decoration: InputDecoration(
          hintText: "请输入昵称",
          filled: true,
          fillColor: Colors.white,
          contentPadding:
              const EdgeInsets.symmetric(vertical: 0, horizontal: 16),
          enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(20),
              borderSide: BorderSide(color: Colors.white, width: 2.0)),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
            borderSide: BorderSide(
              color: Colors.white,
              width: 2,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDes() {
    return Container(
      margin: const EdgeInsets.only(top: 24, bottom: 12, left: 15, right: 15),
      child: TextField(
        controller: _desEditController,
        onChanged: (value) {
          setState(() {
            // checkLoginText();
          });
        },
        style: TextStyle(height: 1.5),
        cursorColor: Colors.redAccent,
        enableSuggestions: false,
        autocorrect: false,
        maxLength: 50,
        maxLines: 4,
        minLines: 4,
        decoration: InputDecoration(
          hintText: "请输入简介",
          filled: true,
          fillColor: Colors.white,
          contentPadding:
              const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
          enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(20),
              borderSide: BorderSide(color: Colors.white, width: 2.0)),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
            borderSide: BorderSide(
              color: Colors.white,
              width: 2,
            ),
          ),
        ),
      ),
    );
  }
}

class Cell extends StatelessWidget {
  const Cell(
    this.text, {
    Key key,
    this.border = true,
    this.showRight = true,
    this.right,
    this.onTap,
  }) : super(key: key);

  /// 底部 border 是否显示
  final bool border;
  final bool showRight;

  /// 右侧文字
  final String text;

  /// 右侧内容
  final Widget right;

  /// 点击回调
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      child: InkWell(
        onTap: onTap,
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(20)),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                  width: toRpx(size: 250),
                  child: Text(
                    text,
                    style: TextStyle(
                      fontSize: WcaoTheme.fsL,
                      color: WcaoTheme.base,
                    ),
                  )),
              Row(children: [
                Container(
                    alignment: Alignment.centerRight,
                    width: toRpx(size: 250),
                    child: right),
                showRight
                    ? Container(
                        margin: EdgeInsets.only(left: 5),
                        child: Icon(
                          Icons.arrow_forward_ios,
                          size: WcaoTheme.fsXl,
                          color: WcaoTheme.secondary,
                        ),
                      )
                    : Container()
              ])
            ],
          ),
        ),
      ),
    );
  }
}
